import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../user/entities/user.entity';
import { UserFavorite } from './entities/user-favorite.entity';
import { UserReadingHistory } from './entities/user-reading-history.entity';
import { Comment } from './entities/comment.entity';
import { Novel } from './entities/novel.entity';

@Injectable()
export class ProfileService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(UserFavorite)
    private favoriteRepository: Repository<UserFavorite>,
    @InjectRepository(UserReadingHistory)
    private readingHistoryRepository: Repository<UserReadingHistory>,
    @InjectRepository(Comment)
    private commentRepository: Repository<Comment>,
    @InjectRepository(Novel)
    private novelRepository: Repository<Novel>,
  ) {}

  /**
   * 获取用户统计数据
   */
  async getUserStats(userId: number) {
    const favoriteCount = await this.favoriteRepository.count({
      where: { userId },
    });

    const readingHistoryCount = await this.readingHistoryRepository.count({
      where: { userId },
    });

    const commentCount = await this.commentRepository.count({
      where: { userId },
    });

    return {
      favoriteCount,
      readingHistoryCount,
      commentCount,
    };
  }

  /**
   * 获取用户阅读统计
   */
  async getReadingStats(userId: number) {
    const totalRead = await this.readingHistoryRepository.count({
      where: { userId },
    });

    // 获取最近阅读的小说
    const recentReading = await this.readingHistoryRepository.find({
      where: { userId },
      relations: ['novel', 'novel.masterCategory'],
      order: { lastReadAt: 'DESC' },
      take: 5,
    });

    // 获取最常阅读的分类
    const categoryStats = await this.readingHistoryRepository
      .createQueryBuilder('history')
      .leftJoinAndSelect('history.novel', 'novel')
      .leftJoinAndSelect('novel.masterCategory', 'masterCategory')
      .select(['category.id', 'category.name', 'COUNT(*) as count'])
      .where('history.userId = :userId', { userId })
      .groupBy('category.id')
      .orderBy('count', 'DESC')
      .limit(5)
      .getRawMany();

    return {
      totalRead,
      recentReading,
      categoryStats,
    };
  }

  /**
   * 获取用户评论列表
   */
  async getUserComments(userId: number, options: any = {}) {
    const { page = 1, limit = 10 } = options;
    const skip = (page - 1) * limit;

    const [comments, total] = await this.commentRepository.findAndCount({
      where: { userId },
      relations: ['novel', 'novel.masterCategory'],
      order: { createdAt: 'DESC' },
      take: limit,
      skip,
    });

    return {
      items: comments,
      meta: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
        hasNext: page * limit < total,
        hasPrev: page > 1,
      },
    };
  }

  /**
   * 获取用户活动时间线
   */
  async getUserActivityTimeline(userId: number, limit: number = 20) {
    const activities: any[] = [];

    // 获取最近的阅读记录
    const readingHistory = await this.readingHistoryRepository.find({
      where: { userId },
      relations: ['novel', 'chapter'],
      order: { lastReadAt: 'DESC' },
      take: Math.floor(limit / 3),
    });

    readingHistory.forEach((history) => {
      activities.push({
        type: 'reading',
        title: `开始阅读《${history.novel.title}》`,
        subtitle: history.chapter ? history.chapter.title : '未指定章节',
        timestamp: history.lastReadAt,
        data: {
          novelId: history.novelId,
          chapterId: history.chapterId,
          readProgress: history.readProgress,
        },
      });
    });

    // 获取最近的评论
    const comments = await this.commentRepository.find({
      where: { userId },
      relations: ['novel'],
      order: { createdAt: 'DESC' },
      take: Math.floor(limit / 3),
    });

    comments.forEach((comment) => {
      activities.push({
        type: 'comment',
        title: `评论了《${comment.novel.title}》`,
        subtitle:
          comment.content.substring(0, 50) +
          (comment.content.length > 50 ? '...' : ''),
        timestamp: comment.createdAt,
        data: {
          novelId: comment.novelId,
          commentId: comment.id,
          content: comment.content,
        },
      });
    });

    // 获取最近的收藏
    const favorites = await this.favoriteRepository.find({
      where: { userId },
      relations: ['novel'],
      order: { createdAt: 'DESC' },
      take: Math.floor(limit / 3),
    });

    favorites.forEach((favorite) => {
      activities.push({
        type: 'favorite',
        title: `收藏了《${favorite.novel.title}》`,
        subtitle: '加入个人收藏',
        timestamp: favorite.createdAt,
        data: {
          novelId: favorite.novelId,
        },
      });
    });

    // 按时间排序
    activities.sort(
      (a, b) =>
        new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
    );

    return activities.slice(0, limit);
  }

  /**
   * 获取用户推荐的小说
   */
  async getRecommendedNovels(userId: number, limit: number = 10): Promise<any> {
    // 基于用户阅读历史和收藏记录推荐
    const readingHistory = await this.readingHistoryRepository.find({
      where: { userId },
      relations: ['novel', 'novel.masterCategory'],
      order: { lastReadAt: 'DESC' },
      take: 5,
    });

    const favorites = await this.favoriteRepository.find({
      where: { userId },
      relations: ['novel', 'novel.masterCategory'],
      order: { createdAt: 'DESC' },
      take: 5,
    });

    // 收集已读/收藏的小说ID
    const novelIds = new Set([
      ...readingHistory.map((h) => h.novelId),
      ...favorites.map((f) => f.novelId),
    ]);

    if (novelIds.size === 0) {
      // 如果用户没有任何记录，返回热门小说
      return this.novelRepository.find({
        where: { status: 1 }, // 假设1是连载状态
        relations: ['category'],
        order: { readCount: 'DESC' },
        take: limit,
      });
    }

    // 基于用户偏好推荐同类型的高分小说
    const categories = Array.from(
      new Set([
        ...readingHistory.map((h) => h.novel.masterCategory?.id).filter(Boolean),
        ...favorites.map((f) => f.novel.masterCategory?.id).filter(Boolean),
      ]),
    );

    const recommendedNovels = await this.novelRepository.find({
      where: [
        { status: 1 },
        categories.length > 0 ? { masterCategoryId: categories as any } : {},
        { id: Array.from(novelIds) as any },
      ],
      relations: ['category'],
      order: { ratingScore: 'DESC', readCount: 'DESC' },
      take: limit,
    });

    return recommendedNovels;
  }

  /**
   * 获取用户阅读偏好分析
   */
  async getReadingPreferences(userId: number) {
    const readingHistory = await this.readingHistoryRepository.find({
      where: { userId },
      relations: ['novel', 'novel.masterCategory'],
      order: { lastReadAt: 'DESC' },
      take: 100, // 分析最近100条记录
    });

    const categoryCount: { [key: string]: number } = {};
    const timeCount: { [key: string]: number } = {};

    readingHistory.forEach((history) => {
      const category = history.novel.masterCategory;
      if (category) {
        categoryCount[category.id] = (categoryCount[category.id] || 0) + 1;
      }

      const hour = new Date(history.lastReadAt).getHours();
      timeCount[hour] = (timeCount[hour] || 0) + 1;
    });

    // 分析阅读时间段
    let peakTime = '未知';
    let maxCount = 0;
    for (const [hour, count] of Object.entries(timeCount)) {
      if (count > maxCount) {
        maxCount = count;
        peakTime = `${hour}:00-${parseInt(hour) + 1}:00`;
      }
    }

    // 找出最喜爱的分类
    let favoriteCategory = null;
    let maxCategoryCount = 0;
    for (const [categoryId, count] of Object.entries(categoryCount)) {
      if (count > maxCategoryCount) {
        maxCategoryCount = count;
        favoriteCategory = parseInt(categoryId) as any;
      }
    }

    return {
      favoriteCategory,
      favoriteCategoryCount: maxCategoryCount,
      peakReadingTime: peakTime,
      totalBooksRead: readingHistory.length,
      averageBooksPerWeek:
        Math.round((readingHistory.length / 30) * 7 * 10) / 10, // 假设30天内的数据
    };
  }

  /**
   * 获取用户详细信息
   */
  async getUserProfile(userId: number) {
    const user = await this.userRepository.findOne({
      where: { id: userId },
      select: [
        'id',
        'username',
        'nickname',
        'email',
        'avatar',
        'gender',
        'createdAt',
      ],
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    return user;
  }

  /**
   * 更新用户信息
   */
  async updateProfile(userId: number, updateData: any) {
    await this.userRepository.update(userId, updateData);
    return this.getUserProfile(userId);
  }

  /**
   * 修改密码
   */
  async changePassword(
    userId: number,
    oldPassword: string,
    newPassword: string,
  ) {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    // 这里应该验证旧密码，简化实现
    await this.userRepository.update(userId, {
      passwordHash: newPassword, // 实际应该hash
    });

    return { success: true };
  }

  /**
   * 更新头像
   */
  async updateAvatar(userId: number, avatarUrl: string) {
    await this.userRepository.update(userId, { avatar: avatarUrl });
    return { avatarUrl };
  }

  /**
   * 更新阅读偏好
   */
  async updateReadingPreferences(userId: number, preferences: any) {
    // 这里应该保存到用户偏好设置表，简化实现
    return { success: true, preferences };
  }

  /**
   * 获取最近阅读
   */
  async getRecentReading(userId: number, limit: number) {
    return this.readingHistoryRepository.find({
      where: { userId },
      relations: ['novel', 'chapter'],
      order: { lastReadAt: 'DESC' },
      take: limit,
    });
  }

  /**
   * 获取收藏分类统计
   */
  async getFavoriteCategories(userId: number) {
    const result = await this.favoriteRepository
      .createQueryBuilder('favorite')
      .leftJoinAndSelect('favorite.novel', 'novel')
      .leftJoinAndSelect('novel.masterCategory', 'masterCategory')
      .select(['category.id', 'category.name', 'COUNT(*) as count'])
      .where('favorite.userId = :userId', { userId })
      .groupBy('category.id')
      .orderBy('count', 'DESC')
      .getRawMany();

    return result;
  }

  /**
   * 获取阅读时长统计
   */
  async getReadingTimeStats(userId: number, period: string) {
    // 简化实现，实际应该根据阅读时长计算
    const readingHistory = await this.readingHistoryRepository.find({
      where: { userId },
      order: { lastReadAt: 'DESC' },
    });

    // 模拟统计数据
    return {
      period,
      totalReadingTime: readingHistory.length * 30, // 假设每章30分钟
      dailyAverage: 45, // 每日平均分钟
      weeklyStats: this.generateWeeklyStats(),
    };
  }

  /**
   * 清空用户活动记录
   */
  async clearUserActivities(userId: number) {
    await this.readingHistoryRepository.delete({ userId });
    return { success: true };
  }

  /**
   * 导出用户数据
   */
  async exportUserData(userId: number) {
    const profile = await this.getUserProfile(userId);
    const stats = await this.getUserStats(userId);
    const preferences = await this.getReadingPreferences(userId);

    return {
      profile,
      stats,
      preferences,
      exportTime: new Date(),
    };
  }

  /**
   * 注销账号
   */
  async deleteAccount(userId: number, password: string) {
    // 这里应该验证密码，简化实现
    await this.userRepository.delete(userId);
    return { success: true };
  }

  /**
   * 获取隐私设置
   */
  async getPrivacySettings(userId: number) {
    // 简化实现，实际应该从配置表读取
    return {
      profilePublic: false,
      readingHistoryPublic: false,
      favoritesPublic: false,
      commentsPublic: true,
      statsPublic: false,
    };
  }

  /**
   * 更新隐私设置
   */
  async updatePrivacySettings(userId: number, settings: any) {
    // 简化实现，实际应该保存到配置表
    return { success: true, settings };
  }

  /**
   * 生成周统计数据
   */
  private generateWeeklyStats(): any[] {
    const stats: any[] = [];
    for (let i = 6; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      stats.push({
        date: date.toISOString().split('T')[0],
        readingTime: Math.floor(Math.random() * 120) + 10, // 10-130分钟随机
        chaptersRead: Math.floor(Math.random() * 5) + 1, // 1-5章随机
      });
    }
    return stats;
  }
}
